package com.szholly.pro.watergas_server.ps.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;


@Service
public class SafeRoleService {
	
	/**
	 * 获取角色站点信息
	 * @param roleId
	 * @return
	 */
	public List<RowBase> getRoleStationList(String roleId,String waterType){
		List<GlobalParameter> pc = new ArrayList<>();
		pc.add(new GlobalParameter("roleId", roleId));
		pc.add(new GlobalParameter("waterType", waterType));		
		String sql="";
		if(waterType != null){
			if(waterType.equals("8")){
				sql="select t.companyname as name,t.companycode as code,case when t1.guid is null then 0 else 1 end ischeck from qc_companyinfo t"
				   +" left join OC_ROLE_SITE_PRIVILEGE t1 on t.companycode = t1.station_code and t1.role_id = @roleId order by t.companycode";
			}else{
				sql = "select t.name,t.code,case when t1.guid is null then 0 else 1 end ischeck from BC_SITE_INFO t\n" +
						"       left join OC_ROLE_SITE_PRIVILEGE t1 on t.code = t1.station_code and t1.role_id = @roleId\n"+
						" where t.build_status = '0' ";
				sql += " AND t.station_category = @waterType order by t.code";
			}			
		}	
		List<RowBase> result = DataUtil.getSelectRows(sql, pc);
		return result;
	}
	
	/**
	 * 保存角色站点信息
	 * @param roleId
	 * @param stationCodes
	 */
	public void saveRoleStation(String roleId,String[] stationCodes){
		
		try {
			DataUtil.beginTransaction();
			
			String deleteSql = " DELETE from OC_ROLE_SITE_PRIVILEGE WHERE role_id = @ROLE_ID ";
			List<GlobalParameter> pc = new ArrayList<>();
			pc.add(new GlobalParameter("ROLE_ID", roleId));
			
			DataUtil.ExecuteUpdateSql(deleteSql, pc);
			
			for(int i=0;i<stationCodes.length;i++){
				pc.clear();
				String insertSql = " INSERT INTO OC_ROLE_SITE_PRIVILEGE(ROLE_ID,STATION_CODE) VALUES";
				insertSql += "(@ROLE_ID,@STATION_CODE)";
				pc.add(new GlobalParameter("ROLE_ID", roleId));
				pc.add(new GlobalParameter("STATION_CODE", stationCodes[i]));
				DataUtil.ExecuteUpdateSql(insertSql, pc);
			}
			
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
		}
	}
}
